import { start as startAdmin, PermissionConfig } from "maishu-chitu-admin";
import { createDataContext as createGatewayDataContext } from "maishu-node-auth/gateway";
import path = require("path");
import { ConnectionConfig } from "mysql";
import { merchantRoleId, stationPath } from "./global";
import { LogLevel } from "maishu-node-mvc";

export { merchantRoleId } from "./global";
export { stationPath } from "./global";

export type Settings = {
    port: number,
    gateway: string,
    permissionDB: ConnectionConfig,
    gatewayDB: ConnectionConfig,
    logLevel: LogLevel
}

export async function start(settings: Settings) {
    let permissions: PermissionConfig = {};
    permissions[`${stationPath}*`] = { roleIds: [merchantRoleId] };
    startAdmin({
        port: settings.port,
        rootDirectory: __dirname,
        station: {
            gateway: settings.gateway,
            path: stationPath,
            permissions: permissions
        },
        virtualPaths: {
            "node_modules": path.join(__dirname, "../node_modules")
        }
    })

    let dc = await createGatewayDataContext({ db: settings.gatewayDB, logLevel: settings.logLevel });
    let merchantRole = await dc.roles.findOne(merchantRoleId);
    if (merchantRole == null) {
        merchantRole = { id: merchantRoleId, name: "商户", create_date_time: new Date(Date.now()) };
        await dc.roles.insert(merchantRole);
    }
}



